const product_model = require('../../models/project/index');
const BaseComponent = require('../../prototype/baseComponent');
class Project extends BaseComponent {
  constructor() {
    super()
  }
  //获取项目列表
  getProjectList = async (req, res, next) => {
    try {
      let { page = 1, limit = 10 } = req.query
      let projectList = await product_model.find({}, { '__v': 0 }, { lean: true }).populate('category_id').skip(Number((page - 1) * limit)).limit(Number(limit))
      let total = await product_model.estimatedDocumentCount()
      projectList.forEach((item) => {
        item.start_time = this.formatTime(item.start_time)
        item.end_time = this.formatTime(item.end_time)
        if (item.category_id) {
          item.category_Info = item.category_id
          item.category_id = item.category_id._id
        }
      })
      let data = {
        list: projectList,
        total: total
      }
      this.sendSuccess(res, data, '查询成功')
    } catch (error) {
      this.sendError(res, error)
    }
  }
  //新增项目
  newProject = async (req, res, next) => {
    try {
      // await this.projectJoi(req.body)
      let { name = '', describe = '', remarks = '', start_time = '', end_time = '', url = '', img_url, category_id } = req.body
      if (!start_time || !end_time) throw new Error("请填写开始时间或结束时间")
      let new_project = {
        _id: this.createId(),
        name: name,
        start_time: start_time,
        end_time: end_time,
        describe: describe,
        img_url: img_url,
        category_id: category_id
      }
      await product_model.create(new_project)
      this.sendSuccess(res, '', '新增成功')
    } catch (error) {
      this.sendError(res, error)
    }
  }
  //编辑项目
  editProject = async (req, res, next) => {
    try {
      // await this.projectJoi(req.body)
      let { _id = '' } = req.body
      if (!_id) throw new Error("请填写项目id")
      let details = await product_model.findOneAndUpdate({ _id: _id }, { $set: req.body })
      if (!details) throw new Error("没有此项目，请检查项目id是否正确")
      this.sendSuccess(res, '', '修改成功')
    } catch (error) {
      this.sendError(res, error)
    }
  }
  //删除项目
  delProject = async (req, res, next) => {
    try {
      let { _id = '' } = req.body
      if (!_id) throw new Error("请填写项目id")
      let details = await product_model.findOneAndRemove({ _id: _id })
      if (!details) throw new Error("没有此项目，请检查项目id是否正确")
      this.sendSuccess(res, '', '删除成功')
    } catch (error) {
      this.sendError(res, error)
    }
  }
}
module.exports = new Project()